package org.jflame.auth.authc.assist;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;

public class FailureRedisCounter extends FailureCounter {

    protected int expireInSecond = 600;
    /**
     * 统计器唯一名称标识，用于区分不同统计器的数据
     */
    protected final String name;
    private RedisTemplate<String,Integer> redisTemplate;

    public FailureRedisCounter(RedisTemplate<String,Integer> redisTemplate) {
        this(0, 0, redisTemplate, null);
    }

    public FailureRedisCounter(int maxFailures, int _expireInSecond, RedisTemplate<String,Integer> _redisTemplate,
            String counterName) {
        super(maxFailures);
        redisTemplate = _redisTemplate;
        name = counterName == null ? getClass().getSimpleName() : counterName;
        if (expireInSecond > 0) {
            expireInSecond = _expireInSecond;
        }
    }

    @Override
    public int getFailures(String account) {
        String key = uniqueKey(account);
        Integer qty = redisTemplate.opsForValue()
                .get(key);
        return qty == null ? 0 : qty;
    }

    private String uniqueKey(String account) {
        return name + ":" + account;
    }

    @Override
    protected int increment(String account) {
        String key = uniqueKey(account);
        int loginFailNum = redisTemplate.opsForValue()
                .increment(key)
                .intValue();
        if (loginFailNum == 1) {
            redisTemplate.expire(key, expireInSecond, TimeUnit.SECONDS);
        }
        return loginFailNum;
    }

    @Override
    public void clear(String account) {
        redisTemplate.delete(uniqueKey(account));
    }

}
